home *** CD-ROM | disk | FTP | other *** search
/ Aminet 40 / Aminet 40 (2000)(Schatztruhe)[!][Dec 2000].iso / Aminet / dev / lang / Python16.lha / Python-1.6 / Lib / Python1.6 / SimpleHTTPServer.py < prev    next >
Encoding:
Python Source  |  2000-05-09  |  5.5 KB  |  183 lines

  1. """Simple HTTP Server.
  2.  
  3. This module builds on BaseHTTPServer by implementing the standard GET
  4. and HEAD requests in a fairly straightforward manner.
  5.  
  6. """
  7.  
  8.  
  9. __version__ = "0.4"
  10.  
  11.  
  12. import os
  13. import string
  14. import posixpath
  15. import BaseHTTPServer
  16. import urllib
  17. import cgi
  18. from StringIO import StringIO
  19.  
  20.  
  21. class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
  22.  
  23.     """Simple HTTP request handler with GET and HEAD commands.
  24.  
  25.     This serves files from the current directory and any of its
  26.     subdirectories.  It assumes that all files are plain text files
  27.     unless they have the extension ".html" in which case it assumes
  28.     they are HTML files.
  29.  
  30.     The GET and HEAD requests are identical except that the HEAD
  31.     request omits the actual contents of the file.
  32.  
  33.     """
  34.  
  35.     server_version = "SimpleHTTP/" + __version__
  36.  
  37.     def do_GET(self):
  38.         """Serve a GET request."""
  39.         f = self.send_head()
  40.         if f:
  41.             self.copyfile(f, self.wfile)
  42.             f.close()
  43.  
  44.     def do_HEAD(self):
  45.         """Serve a HEAD request."""
  46.         f = self.send_head()
  47.         if f:
  48.             f.close()
  49.  
  50.     def send_head(self):
  51.         """Common code for GET and HEAD commands.
  52.  
  53.         This sends the response code and MIME headers.
  54.  
  55.         Return value is either a file object (which has to be copied
  56.         to the outputfile by the caller unless the command was HEAD,
  57.         and must be closed by the caller under all circumstances), or
  58.         None, in which case the caller has nothing further to do.
  59.  
  60.         """
  61.         path = self.translate_path(self.path)
  62.         if os.path.isdir(path):
  63.             f = self.list_directory(path)
  64.             if f is None:
  65.                 return None
  66.             ctype = "text/HTML"
  67.         else:
  68.             try:
  69.                 f = open(path, 'rb')
  70.             except IOError:
  71.                 self.send_error(404, "File not found")
  72.                 return None
  73.             ctype = self.guess_type(path)
  74.         self.send_response(200)
  75.         self.send_header("Content-type", ctype)
  76.         self.end_headers()
  77.         return f
  78.  
  79.     def list_directory(self, path):
  80.         try:
  81.             list = os.listdir(path)
  82.         except os.error:
  83.             self.send_error(404, "No permission to list directory");
  84.             return None
  85.         list.sort(lambda a, b: cmp(a.lower(), b.lower()))
  86.         f = StringIO()
  87.         f.write("<h2>Directory listing for %s</h2>\n" % self.path)
  88.         f.write("<hr>\n<ul>\n")
  89.         for name in list:
  90.             fullname = os.path.join(path, name)
  91.             displayname = name = cgi.escape(name)
  92.             if os.path.islink(fullname):
  93.                 displayname = name + "@"
  94.             elif os.path.isdir(fullname):
  95.                 displayname = name + "/"
  96.                 name = name + os.sep
  97.             f.write('<li><a href="%s">%s</a>\n' % (name, displayname))
  98.         f.write("</ul>\n<hr>\n")
  99.         f.seek(0)
  100.         return f
  101.  
  102.     def translate_path(self, path):
  103.         """Translate a /-separated PATH to the local filename syntax.
  104.  
  105.         Components that mean special things to the local file system
  106.         (e.g. drive or directory names) are ignored.  (XXX They should
  107.         probably be diagnosed.)
  108.  
  109.         """
  110.         path = posixpath.normpath(urllib.unquote(path))
  111.         words = string.splitfields(path, '/')
  112.         words = filter(None, words)
  113.         path = os.getcwd()
  114.         for word in words:
  115.             drive, word = os.path.splitdrive(word)
  116.             head, word = os.path.split(word)
  117.             if word in (os.curdir, os.pardir): continue
  118.             path = os.path.join(path, word)
  119.         return path
  120.  
  121.     def copyfile(self, source, outputfile):
  122.         """Copy all data between two file objects.
  123.  
  124.         The SOURCE argument is a file object open for reading
  125.         (or anything with a read() method) and the DESTINATION
  126.         argument is a file object open for writing (or
  127.         anything with a write() method).
  128.  
  129.         The only reason for overriding this would be to change
  130.         the block size or perhaps to replace newlines by CRLF
  131.         -- note however that this the default server uses this
  132.         to copy binary data as well.
  133.  
  134.         """
  135.  
  136.         BLOCKSIZE = 8192
  137.         while 1:
  138.             data = source.read(BLOCKSIZE)
  139.             if not data: break
  140.             outputfile.write(data)
  141.  
  142.     def guess_type(self, path):
  143.         """Guess the type of a file.
  144.  
  145.         Argument is a PATH (a filename).
  146.  
  147.         Return value is a string of the form type/subtype,
  148.         usable for a MIME Content-type header.
  149.  
  150.         The default implementation looks the file's extension
  151.         up in the table self.extensions_map, using text/plain
  152.         as a default; however it would be permissible (if
  153.         slow) to look inside the data to make a better guess.
  154.  
  155.         """
  156.  
  157.         base, ext = posixpath.splitext(path)
  158.         if self.extensions_map.has_key(ext):
  159.             return self.extensions_map[ext]
  160.         ext = string.lower(ext)
  161.         if self.extensions_map.has_key(ext):
  162.             return self.extensions_map[ext]
  163.         else:
  164.             return self.extensions_map['']
  165.  
  166.     extensions_map = {
  167.             '': 'text/plain',   # Default, *must* be present
  168.             '.html': 'text/html',
  169.             '.htm': 'text/html',
  170.             '.gif': 'image/gif',
  171.             '.jpg': 'image/jpeg',
  172.             '.jpeg': 'image/jpeg',
  173.             }
  174.  
  175.  
  176. def test(HandlerClass = SimpleHTTPRequestHandler,
  177.          ServerClass = BaseHTTPServer.HTTPServer):
  178.     BaseHTTPServer.test(HandlerClass, ServerClass)
  179.  
  180.  
  181. if __name__ == '__main__':
  182.     test()
  183.